package com.guigu.tms.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.guigu.tms.commons.user.entity.AddressBook;
import com.guigu.tms.user.service.IAddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.List;

/**
 * <p>
 * 地址簿 前端控制器
 * </p>
 *
 * @author zwj
 * @since 2022-10-16
 */
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private IAddressBookService addressBookService;

    @GetMapping("getAddressBook")
    public List<AddressBook> getAddressBook(String memberId){
        QueryWrapper<AddressBook> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",memberId);
        return addressBookService.list(wrapper);
    }
    @PostMapping("addAddressBook")
    public boolean addAddressBook(@RequestBody AddressBook addressBook){
        if(addressBook.getIsDefault()){
            UpdateWrapper<AddressBook> wrapper = new UpdateWrapper<>();
            wrapper.set("is_default",false);
            wrapper.eq("user_id",addressBook.getUserId());
            addressBookService.update(wrapper);
        }
        return addressBookService.save(addressBook);
    }

    @PutMapping("updateAddressBook")
    public boolean updateAddressBook(@RequestBody AddressBook addressBook){
        if(addressBook.getIsDefault()){
            UpdateWrapper<AddressBook> wrapper = new UpdateWrapper<>();
            wrapper.set("is_default",false);
            wrapper.eq("user_id",addressBook.getUserId());
            addressBookService.update(wrapper);
        }
       return addressBookService.updateById(addressBook);
    }

    @DeleteMapping("deleteAddressBook/{id}")
    public boolean deleteAddressBook(@PathVariable("id") String id){
        return addressBookService.removeById(id);
    }

    @GetMapping("getDefaultAddressBook")
    public AddressBook getDefaultAddressBook(String userId){
        QueryWrapper<AddressBook> wrapper=new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        wrapper.eq("is_default", true);
        AddressBook one = addressBookService.getOne(wrapper);
        return one;
    }

    @PutMapping("setDefaultAddressBook")
    public boolean setDefaultAddressBook(String userId,String id){
        UpdateWrapper<AddressBook> wrapper = new UpdateWrapper<>();
        wrapper.set("is_default",false);
        wrapper.eq("user_id",userId);
        addressBookService.update(wrapper);
        UpdateWrapper<AddressBook> wrapper1 = new UpdateWrapper<>();
        wrapper1.eq("id",id);
        wrapper1.set("is_default",true);
        return addressBookService.update(wrapper1);
    }

    @GetMapping("getAddressBookById")
    AddressBook getAddressBookById(String id){
        return addressBookService.getById(id);
    }

}
